// 导入 createRouter 用于创建路由的函数
// createWebHashHistory代表使用hash模式的路由
import store from '@/store'
import { createRouter, createWebHashHistory } from 'vue-router'

// 配置路由路径和组件的映射关系
const Layout = () => import('@/views/Layout')
const Home = () => import('@/views/home/index.vue')
const TopCategory = () => import('@/views/category/index.vue')
const SubCategory = () => import('@/views/category/sub.vue')
const Goods = () => import('@/views/goods/index')
const Login = () => import('@/views/login')
const LoginCallback = () => import('@/views/login/callback')
const Cart = () => import('@/views/cart/index.vue')
const PayCheckout = () => import('@/views/member/pay/checkout')
const PayIndex = () => import('@/views/member/pay/index')
const Callback = () => import('@/views/member/pay/callback.vue')
const MemberLayout = () => import('@/views/member/Layout')
const MemberHome = () => import('@/views/member/home/index.vue')
const routes = [
  {
    path: '/',
    component: Layout,
    children: [
      { path: '', component: Home }, // 首页组件
      { path: 'category/:id', component: TopCategory }, // 一级分类页
      { path: 'category/sub/:id', component: SubCategory }, // 二级分类页
      { path: '/product/:id', component: Goods }, // 商品详情
      { path: 'cart', component: Cart },
      { path: '/member/checkout', component: PayCheckout },
      { path: '/member/pay', component: PayIndex },
      { path: '/member/pay/callback', component: Callback },
      {
        path: '/member',
        component: MemberLayout,
        children: [
          { path: '/member', component: MemberHome }
        ]
      }
    ]
  },
  { path: '/login', component: Login }, // 登录页面
  { path: '/login/callback', component: LoginCallback }
]
// 创建路由实例
const router = createRouter({
  // 使用hash方式实现路由
  history: createWebHashHistory(),
  // 配置路由规则，写法和之前一样
  routes,
  // 路由进阶 - 滚动行为
  scrollBehavior (to, from, savedPosition) {
    // console.log(to.path)
    // console.log(savedPosition)
    if (to.path !== '/') {
      //  始终滚动到顶部
      // return { top: 0 }
      // 始终滚动到顶部，behavior: 'smooth' 平滑滚动效果
      return { top: 0, behavior: 'smooth' }
      // Vue2返回的是 { x:0 , y:0 }
      // Vue3返回的是 { left:0 , top:0 }
    } else {
      return savedPosition
    }
  }
})

// 前置导航守卫
router.beforeEach((to, from) => {
  // 用户信息
  const { token } = store.state.user.profile
  // 跳转去member开头的地址却没有登录
  if (to.path.startsWith('/member') && !token) {
    return { path: '/login', query: { redirectUrl: to.fullPath } }
  }
})
export default router
